package com.bsj.travel.security.feign;

import com.bsj.travel.constant.SecurityConstants;
import com.bsj.travel.util.ServletUtils;
import com.bsj.travel.util.StringUtils;
import com.bsj.travel.util.ip.IpUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author yinhao
 * @version 1.0
 * @description Feign 请求拦截
 * @date 2023/11/2
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        if (StringUtils.isNotNull(httpServletRequest)) {
            Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
            //传递用户请求头，防丢失
            String userId = headers.get(SecurityConstants.USER_ID);
            if (StringUtils.isNotEmpty(userId)) {
                requestTemplate.header(SecurityConstants.USER_ID, userId);
            }
            String userName = headers.get(SecurityConstants.USER_NAME);
            if (StringUtils.isNotEmpty(userName)) {
                requestTemplate.header(SecurityConstants.USER_NAME);
            }
            String tokenAuth = headers.get(SecurityConstants.TOKEN_AUTH);
            if (StringUtils.isNotEmpty(tokenAuth)) {
                requestTemplate.header(SecurityConstants.TOKEN_AUTH, tokenAuth);
            }
            //配置客户端IP
            requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr(httpServletRequest));
        }
    }
}
